<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/17
 * Time: 10:41
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\CommonVar;
use common\models\CreateCode;
use common\models\DAO\User;
use common\models\DAO\UserCode;
use common\models\DAO\UserLoginLog;
use common\models\Http;
use common\msg\UserMsg;

class LoginService {
	//检查微信用户是否已注册
	public static function wxCheck($unionID)
	{
		if($userInfo=User::findOne(array('unionID'=>$unionID)))
		{
			$userInfo=$userInfo->attributes;
			$return['msg'] = 'blacklist';
			//账号不可用
			if(intval($userInfo['status']) != 1) return $return;
			//账号可用 写登录日志
			$loginLog = new UserLoginLog();
			$loginLog->userID = $userInfo['id'];
			$loginLog->loginTime = time();
			$loginLog->loginIP = CommonFunction::get_client_ip();
			$loginLog->result = 1;
			$loginLog->save();
			//写session
			$user_info = array('userID'=>$userInfo['id'], 'openID'=>$userInfo['openID'], 'tel'=>CommonFunction::decrypt($userInfo['phone']), 'name'=>$userInfo['realName'],'head'=>$userInfo['avatar'], 'recID'=>$userInfo['recID'], 'isNew'=>$userInfo['isNew']);
			$user_info['pwd']=3;
			Http::session('user', $user_info);
			$return['isNew'] = $userInfo['isNew'];
			return $return;
		}else{
			return false;
		}
	}
	
    public static function validate($data,$app = false){
        $phone = CommonFunction::encrypt($data['tel']);
        $userModel = User::findOne(array('phone'=>$phone));
        $error['status'] = 0;
        $error['msg'] = UserMsg::$time_out;
        if(!$userModel){
            $error['msg'] = UserMsg::$not_found;
            return $error;
        }
        $ip = CommonFunction::get_client_ip();
        $userInfo = $userModel->attributes;
        if(intval($userInfo['status']) != 1)
            return $error;
        $userID = $userInfo['id'];
        $today = time();
        $now = $today - 60*3;
        $encrypt = $userInfo['encrypt'];
        $loginPassword = $userInfo['loginPassword'];
        $password = CommonFunction::encryptPassword($data['password'], $encrypt);
        $loginLog = new UserLoginLog();
        $loginLog->userID = $userID;
        $loginLog->loginTime = $today;
        $loginLog->loginIP = $ip;
        $log = $loginLog->find()->where(array('userID'=>$userID,'result'=>0))->andFilterWhere(['>', 'loginTime', $now])->count();
        if($log > 3){
            $error['code'] = 1;
            if(!isset($data['code'])){
                $error['msg'] = UserMsg::$code_input;
                $error['code'] = 1;
                return $error;
            }
            //出现验证码
            $code_name = 'wap_login';
            if(!empty($data['code_name']))
                $code_name = $data['code_name'];
            $codeModel = new CreateCode(array('name'=>md5($code_name)));
            if($app){
                $code =  $codeModel->getAppCode();
            }else{
                $code =  $codeModel->getVerifyCode();
            }
            if($data['code'] != $code){
                $error['msg'] = UserMsg::$code_error;
                $error['code'] = 1;
                return $error;
            }
        }
        if($loginPassword != $password){
            $error['msg'] = UserMsg::$password_error;
            $loginLog->save();
            return $error;
        }else{
            $user_info = array('userID'=>$userInfo['id'], 'openID'=>$userInfo['openID'], 'tel'=>$data['tel'], 'name'=>$userInfo['realName'],'head'=>$userInfo['avatar'], 'recID'=>$userInfo['recID'], 'isNew'=>$userInfo['isNew']);
            $user_info['pwd'] = (CommonFunction::checkPasswordStrength($data['password']));
            $return = array('status'=>1);
            if(!empty($data['unionID'])){
                if(isset($data['openID'])){
                    $userModel->openID = $data['openID'];
                    $user_info['openID'] = $data['openID'];
                }
               /* $return['recID']  = '';
                !empty($userInfo['recID']) && $return['recID']  = $userInfo['recID'];
                if(empty($userInfo['recID']) && isset($data['recID'])){
                    $userModel->recID = $data['recID'];
                    $return['recID'] = $data['recID'];
                }*/
                $userModel->unionID = $data['unionID'];
				//微信信息
				if(Http::session('avatar'))
				{
					//头像
					$userModel->avatar = Http::session('avatar')['headimgurl'];
				    /*	//国家
					$userModel->country=Http::session('avatar')['country'];
					//省份
					$userModel->province=Http::session('avatar')['province'];
					//城市
					$userModel->city=Http::session('avatar')['city'];
					//性别
					$userModel->sex=Http::session('avatar')['sex'];*/
					$user_info['head'] = Http::session('avatar')['headimgurl'];
				}
                $user_result = $userModel->save();
                if(!$user_result){
                    return $error;
                }
                $user_info['unionID'] = $data['unionID'];
                $return['userID'] = $userModel->id;
            }
            Http::session('user', $user_info);
            $loginLog->result = 1;
            $loginLog->save();


            if($userInfo['isNew'] == 1)
                $return['new'] = 1;


            if($app){
                $key = md5($phone.CommonVar::$encrypt.$password);
                $userModel->appKey = $key;
                $user_result = $userModel->save();
                if(!$user_result)
                    return $error;
                $return['app_key'] = $key;
            }
            return $return;
        }

    }

    public static function app_validate($data){
        $phone = CommonFunction::encrypt($data['tel']);
        $userModel = User::findOne(array('phone'=>$phone));
        $error['status'] = 0;
        $error['msg'] = UserMsg::$time_out;
        if(!$userModel){
            $error['msg'] = UserMsg::$not_found;
            return $error;
        }
        $ip = CommonFunction::get_client_ip();
        $userInfo = $userModel->attributes;
        if(intval($userInfo['status']) != 1)
            return $error;
        $userID = $userInfo['id'];
        $today = time();
        $now = $today - 60*3;
        $encrypt = $userInfo['encrypt'];
        $loginPassword = $userInfo['loginPassword'];
        $password = CommonFunction::encryptPassword($data['password'], $encrypt);
        $loginLog = new UserLoginLog();
        $loginLog->userID = $userID;
        $loginLog->loginTime = $today;
        $loginLog->loginIP = $ip;
        $log = $loginLog->find()->where(array('userID'=>$userID,'result'=>0))->andFilterWhere(['>', 'loginTime', $now])->count();
        if($log > 3){
            $error['code'] = 1;
            if(!isset($data['code'])){
                $error['msg'] = UserMsg::$code_input;
                $error['code'] = 1;
                return $error;
            }
            //出现验证码
            $code_name = 'wap_login';
            if(!empty($data['code_name']))
                $code_name = $data['code_name'];
            $codeModel = new CreateCode(array('name'=>md5($code_name)));
            $code =  $codeModel->getAppCode();
            if($data['code'] != $code){
                $error['msg'] = UserMsg::$code_error;
                $error['code'] = 1;
                return $error;
            }
        }
        if($loginPassword != $password){
            $error['msg'] = UserMsg::$password_error;
            $loginLog->save();
            return $error;
        }else{
            $loginLog->result = 1;
            $loginLog->save();


            if($userInfo['isNew'] == 1)
                $return['new'] = 1;


            $key = md5($phone.CommonVar::$encrypt.$password.$today);
            $userModel->place = $data['typeID'];
            isset($data['token']) && $userModel->token = $data['token'];
            $userModel->place = $data['typeID'];
            $userModel->appKey = $key;
            $user_result = $userModel->save();
            if(!$user_result)
                return $error;
            $return['app_key'] = $key;
            $return['status'] = 1;
            return $return;
        }

    }
    public static function hongbao_bind($data){
        $code = $data['code'];
        $phone = CommonFunction::encrypt($data['tel']);
        $today = time();
        $now = $today - 60;
        $userModel = User::findOne(array('phone'=>$phone));
        $error['status'] = 0;
        $error['msg'] = UserMsg::$time_out;
        if(!$userModel){
            $error['msg'] = UserMsg::$not_found;
            return $error;
        }
        $userInfo = $userModel->attributes;
        if(intval($userInfo['status']) != 1)
            return $error;

        //array('condition' => 'tel=:state', 'params' => array(':state'=>$tel))
        $userCode = UserCode::find()->where(array('tel'=>$phone,  'type'=>3))->andFilterWhere(['>', 'createTime', $now])->orderBy('createTime desc')->asArray()->one();
        if(!$userCode){
            $error['msg'] = UserMsg::$send_error;
            return $error;
        }
        if($userCode['code'] != $code){
            $error['msg'] = UserMsg::$code_error;
            return $error;
        }

        $user_info = array('userID'=>$userInfo['id'], 'openID'=>$userInfo['openID'], 'tel'=>$data['tel'], 'name'=>$userInfo['realName'],'head'=>$userInfo['avatar'], 'recID'=>$userInfo['recID'], 'isNew'=>$userInfo['isNew']);
        $return = array('status'=>1);
        if(!empty($data['unionID'])){
            $userModel->unionID = $data['unionID'];
            if(!empty($data['openID'])){
                $userModel->openID = $data['openID'];
                $user_info['openID'] = $data['openID'];
            }
            $userModel->unionID = $data['unionID'];

            $user_result = $userModel->save();
            if(!$user_result){
                return $error;
            }
            $user_info['unionID'] = $data['unionID'];
        }
        $return['userInfo'] = $user_info;
        $return['userID'] = $userModel->id;
        return $return;


    }
}